/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.kamionowski.supreme.persistence.dao;

import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import org.kamionowski.supreme.persistence.entity.Token;
import org.kamionowski.supreme.persistence.entity.Token_;
import org.springframework.stereotype.Repository;

/**
 *
 * @author soldier
 */
@Repository
public class TokenDAOJPA extends AbstractDAOJPA implements TokenDAO {

    @Override
    public List<Token> selectTokensStartingWithOrderedByResultsCount(String tokenBegin, Integer limit) {
        CriteriaBuilder builder = em.getCriteriaBuilder();
        CriteriaQuery<Token> query = builder.createQuery(Token.class);
        Root<Token> tokenRoot = query.from(Token.class);
        query.select(tokenRoot);
        query.where(builder.like(tokenRoot.get(Token_.token), tokenBegin + "%"));
        query.orderBy(builder.desc(tokenRoot.get(Token_.resultscount)));
        return em.createQuery(query).setMaxResults(limit).getResultList();
    }

}
